package controllers

import (
	"encoding/json"
	"io"
	"net/http"
	"xmgl/models"

	"github.com/astaxie/beego"
	//"strconv"
)

type SbController struct {
	beego.Controller
}

//API,返回设备内容或PID下的所有设备列表
type SbsController struct {
	beego.Controller
}

//API,返回根据sb_id返回设备内容
type Api_sbController struct {
	beego.Controller
}

func (this *SbController) Get() {
	var (
		menu models.Menu_gl
		user models.Sut_user
	)

	if this.GetSession("USER") == nil {
		//没有取到session值，页面跳转
		http.Redirect(this.Ctx.ResponseWriter, this.Ctx.Request, "/login", http.StatusFound)
	}

	tmp, ok := this.GetSession("USER").(models.Sut_user) //注意类型断言
	if ok {
		user = tmp
	}
	//log.Println("Lyfj.go MainController Get() 从session中取出用户姓名：", user.User_name) //good

	this.Data["WEBSITE"] = "设备管理"
	this.Data["MENU_LEFT"] = menu.Get_left_menu()
	this.Data["MENU_RIGHT"] = menu.Get_right_menu()
	this.Data["USER_NAME"] = user.User_name

	this.Layout = "layout.html"
	this.TplName = "sbgl.html"
	this.LayoutSections = make(map[string]string)
	this.LayoutSections["HtmlHeader"] = "html_header.html"
}

//api,JSON,根据设备类型的ID即pid，返回所有设备列表；根据设备sb_id，返回单个设备内容
func (this *SbsController) Get() {
	var (
		pid   int
		sbs   []models.Sut_sb
		json1 []byte
		err   error
	)
	this.Ctx.Input.Bind(&pid, "pid")
	sbs = models.Get_sbs(pid)
	if len(sbs) > 0 {
		json1, err = json.MarshalIndent(sbs, "", "")
		if err != nil {
			return
		}
		io.WriteString(this.Ctx.ResponseWriter, string(json1[:]))
	} else {
		io.WriteString(this.Ctx.ResponseWriter, "[]")
	}
}

//api,JSON,根据设备ID即sb_id，返回单个设备的内容
func (this *Api_sbController) Get() {
	var (
		sb_id int
		sb    models.Sut_sb
		json1 []byte
		err   error
	)
	this.Ctx.Input.Bind(&sb_id, "sb_id")
	sb, err = models.Get_sb(sb_id)
	if err != nil {
		io.WriteString(this.Ctx.ResponseWriter, "[]")
		return
	}
	json1, err = json.MarshalIndent(sb, "", "")
	if err != nil {
		io.WriteString(this.Ctx.ResponseWriter, "[]")
		return
	}
	io.WriteString(this.Ctx.ResponseWriter, string(json1[:]))

}
